package org.ehe.erp.service.product;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.erp.event.BomArrivalCompleteEvent;
import org.ehe.erp.mapper.product.ErpProductArrivalMapper;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 批次到货检查服务
 * 用于检查BOM物料到货情况，触发质检任务创建
 *
 * @author zhangnn
 * @className BatchArrivalService
 * @description 批次到货状态检查和事件发布
 * @date 2025-09-11 16:00:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BatchArrivalService {

    private final ApplicationEventPublisher eventPublisher;
    private final ErpProductArrivalMapper productArrivalMapper;

    /**
     * 检查BOM是否所有批次物料都已到货
     * 在erp_product_arrival表状态更新时调用此方法
     *
     * @param bomId BOM ID
     */
    public void checkBomArrivalComplete(Long bomId) {
        log.debug("检查BOM {} 的所有批次到货完成状态", bomId);

        try {
            boolean allBatchesArrived = checkAllBatchesArrivedForBom(bomId);

            if (allBatchesArrived) {
                log.info("BOM {} 下所有批次物料已到货，发布BOM到货完成事件", bomId);

                // 获取BOM相关信息
                BomInfo bomInfo = getBomInfo(bomId);
                //获取bom下的采购订单信息
                List<String> purchaseOrders = getAllPurchaseOrdersByBom(bomId);

                // 发布BOM到货完成事件
                BomArrivalCompleteEvent event = new BomArrivalCompleteEvent(
                    bomId, bomInfo.getBomName(),purchaseOrders.get(0)
                );
                eventPublisher.publishEvent(event);
            } else {
                log.debug("BOM {} 仍有批次未完全到货", bomId);
            }

        } catch (Exception e) {
            log.error("检查BOM到货状态失败，BOM ID：{}", bomId, e);
        }
    }

    /**
     * 检查指定BOM下的所有批次是否都已到货
     *
     * @param bomId BOM ID
     * @return true-全部到货，false-仍有未到货
     */
    private boolean checkAllBatchesArrivedForBom(Long bomId) {
        log.debug("检查BOM {} 下所有批次的到货状态", bomId);

        // 查询该BOM下所有的订单编号
        List<String> purchaseOrders = productArrivalMapper.selectPurchaseOrdersByBomId(bomId, null);

        int unArrivedCount = productArrivalMapper.countUnArrivedByPurchaseOrders(purchaseOrders);

        log.debug("BOM {} 下未到货的批次数量: {}", bomId, unArrivedCount);
        return unArrivedCount == 0;
    }

    /**
     * 获取BOM下所有批次ID列表
     */
    private List<String> getAllPurchaseOrdersByBom(Long bomId) {
        return productArrivalMapper.selectPurchaseOrdersByBomId(bomId, 0L);
    }

    /**
     * 获取BOM信息
     */
    private BomInfo getBomInfo(Long bomId) {
        BomInfo bomInfo = new BomInfo();
        bomInfo.setBomId(bomId);
        bomInfo.setBomName("BOM-" + bomId); // 实际应从数据库查询
        bomInfo.setProductId(1L); // 实际应从BOM表查询
        bomInfo.setProductName("产品-" + bomId); // 实际应从产品表查询
        return bomInfo;
    }

    /**
     * 在产品到货状态更新时调用
     * 可以在ErpProductArrivalServiceImpl的updateByBo方法中调用此方法
     *
     * @param arrivalId 到货记录ID
     * @param newStatus 新状态
     */
    public void onProductArrivalStatusChanged(Long arrivalId, Integer newStatus) {
        if (newStatus == 1) { // 状态变为已到货时
            // 获取该到货记录对应的BOM ID
            String orderNo = getOrderNoByArrivalId(arrivalId);
            //根据orderNo获取bomId
            /***将原有的检验bom下的所有订单所有批次到货进行更改为子订单到货  ****/
            Long bomId = getBomInfoByOrderNo(orderNo);
            BomInfo bomInfo = getBomInfo(bomId);
            if(null == bomId){
                bomId = 0L;
                bomInfo.setBomId(0L);
                bomInfo.setBomName("非BOM订单，自主创建采购订单");
            }
            if (orderNo != null) {
                // 检查该BOM下是否所有批次都已到货
                //checkBomArrivalComplete(bomId);
            }
            //检验子订单下，是否所有批次都到货了 add
            List<String> purchaseOrders = new ArrayList<>();
            purchaseOrders.add(orderNo);
            int unArrivedCount = productArrivalMapper.countUnArrivedByPurchaseOrders(purchaseOrders);
            if (unArrivedCount == 0) {
                BomArrivalCompleteEvent event = new BomArrivalCompleteEvent(
                    bomId, bomInfo.getBomName(),purchaseOrders.get(0)
                );
                eventPublisher.publishEvent(event);
            }
            //检验子订单下，是否所有批次都到货了 end
        }
    }

    private Long getBomInfoByOrderNo(String orderNo) {
        return productArrivalMapper.getBomInfoByOrderNo(orderNo);
    }

    /**
     * 根据到货记录ID获取BOM ID
     */
    private String getOrderNoByArrivalId(Long arrivalId) {
        return productArrivalMapper.selectOrderNoById(arrivalId);
    }

    /**
     * BOM信息内部类
     */
    private static class BomInfo {
        private Long bomId;
        private String bomName;
        private Long productId;
        private String productName;

        // getters and setters
        public Long getBomId() { return bomId; }
        public void setBomId(Long bomId) { this.bomId = bomId; }
        public String getBomName() { return bomName; }
        public void setBomName(String bomName) { this.bomName = bomName; }
        public Long getProductId() { return productId; }
        public void setProductId(Long productId) { this.productId = productId; }
        public String getProductName() { return productName; }
        public void setProductName(String productName) { this.productName = productName; }
    }
}
